<template>
  <div class="phonics-lesson-container">
    <el-container>
      <el-header class="header">
        <el-page-header @back="goBack"
          :content="lessonTitle.indexOf('_') > -1 ? lessonTitle.replace('_', '(') + ')' : lessonTitle" />
      </el-header>

      <el-main class="content">
        <div v-if="loading">
          <el-skeleton :rows="5" animated />
        </div>
        <div v-else-if="error">
          <el-alert :title="error" type="error" show-icon :closable="false" />
        </div>
        <div v-else class="lesson-content">
          <!-- 中央展示区域 -->
          <div class="main-display">
            <div class="main-image-container">
              <img v-if="currentItem && currentItem.image" :src="currentItem.image" :alt="currentItem.name"
                class="main-image">
              <el-empty v-else description="暂无图片" />
            </div>

            <div class="audio-controls">
              <el-button @click="playAudio" :loading="isPlaying" size="large" class="play-button">
                {{ isPlaying ? '播放中...' : '▶ 播放' }}
              </el-button>
            </div>
          </div>

          <!-- 缩略图列表 -->
          <div class="thumbnails-container">
            <div class="thumbnails-wrapper">
              <div v-for="(item, index) in items" :key="index" class="thumbnail-item"
                :class="{ active: currentItem && currentItem.id === item.id }" @click="selectItem(item)">
                <img :src="item.image" :alt="item.name">
                <div class="thumbnail-label">{{ item.name }}</div>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ElContainer, ElHeader, ElMain, ElPageHeader, ElSkeleton, ElAlert, ElButton, ElEmpty } from 'element-plus'
import { VideoPlay } from '@element-plus/icons-vue'
import http from '@/utils/http';

export default {
  name: 'PhonicsLesson',
  components: {
    ElContainer,
    ElHeader,
    ElMain,
    ElPageHeader,
    ElSkeleton,
    ElAlert,
    ElButton,
    ElEmpty,
    VideoPlay
  },
  data() {
    return {
      lessonTitle: '',
      items: [],
      currentItem: null,
      loading: true,
      error: null,
      isPlaying: false,
      sound: null
    }
  },
  async mounted() {
    await this.loadLessonData()
  },
  beforeUnmount() {
    if (this.sound) {
      this.sound.pause()
      this.sound = null
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },

    async loadLessonData() {
      try {
        const lessonId = this.$route.params.lessonId  // 例如: "1" 表示 Lesson 1
        const soundId = this.$route.params.soundId    // 例如: "b" 表示字母b的发音

        // 获取课程标题
        this.lessonTitle = `${this.getLessonTitle(lessonId)} - ${soundId.toUpperCase()}`

        // 从后端加载指定音素下的所有示例（包含base64数据）
        const response = await http.get(`/phonics/lessons/${lessonId}/sounds/${soundId}/examples`);
        this.items = response;

        if (this.items.length > 0) {
          this.currentItem = this.items[0]
        }

        this.loading = false
      } catch (err) {
        console.error('Error loading lesson data:', err)
        this.error = '加载课程数据时出错'
        this.loading = false
      }
    },

    getLessonTitle(lessonId) {
      // 优先使用路由参数中的标题，否则使用默认标题
      const titleFromQuery = this.$route.query.title;
      if (titleFromQuery) {
        return decodeURIComponent(titleFromQuery);
      }

      const titles = {
        '1': '辅音学习',
        '2': '短元音学习',
        '3': '长元音学习',
        '4': '双元音学习',
        '5': '混合音学习',
        '6': '静音字母学习',
        '7': '特殊组合学习'
      }
      return titles[lessonId] || '音素学习'
    },

    selectItem(item) {
      this.currentItem = item
      // 停止当前播放的音频
      if (this.sound) {
        this.sound.pause()
        this.sound = null
        this.isPlaying = false
      }
    },

    async playAudio() {
      if (!this.currentItem || !this.currentItem.audio) {
        this.$message.warning('暂无音频资源')
        return
      }

      try {
        // 将base64编码转换为blob
        const byteCharacters = atob(this.currentItem.audio)
        const byteNumbers = new Array(byteCharacters.length)
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i)
        }
        const byteArray = new Uint8Array(byteNumbers)
        const blob = new Blob([byteArray], { type: 'audio/mpeg' })

        // 创建并播放音频
        this.sound = new Audio(URL.createObjectURL(blob))
        this.sound.onplay = () => {
          this.isPlaying = true
        }
        this.sound.onended = () => {
          this.isPlaying = false
        }
        this.sound.onerror = () => {
          this.isPlaying = false
          this.$message.error('音频播放失败')
        }

        this.sound.play()
      } catch (err) {
        console.error('Error loading audio data:', err)
        this.$message.error('音频加载失败')
        this.isPlaying = false
      }
    }
  }
}
</script>

<style scoped>
.phonics-lesson-container {
  padding-top: 0px;
  box-sizing: border-box;
  height: 100%;
}

.header {
  padding: 10px 20px;
  border-bottom: 0px solid #ebeef5;
  font-family: 'DynaPuff', Avenir, Helvetica, Arial, sans-serif;
}

.content {
  padding: 20px;
  height: calc(100vh - 180px);
  box-sizing: border-box;
}

.lesson-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.main-display {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  -background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f4 100%);
  border-radius: 16px;
  padding: 20px;
  -box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.main-image-container {
  width: 100%;
  max-width: 500px;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  overflow-x: hidden;
  border-radius: 12px;
}

.main-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.audio-controls {
  margin-bottom: 30px;
}

.play-button {
  padding: 12px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: none;
  background-color: #409eff;
  color: white;
  font-weight: 500;
  font-size: 16px;
}

.play-button:hover:not(.is-disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  background-color: #337ecc;
}

.play-button:active:not(.is-disabled) {
  transform: translateY(0);
}

.thumbnails-container {
  width: 100%;
  height: fit-content;
  overflow-x: hidden;
  overflow-y: hidden;
  padding: 10px 0;
  background-color: #f5f7fa;
  border-radius: 12px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
}

.thumbnails-wrapper {
  display: flex;
  gap: 15px;
  padding: 15px;
  min-width: min-content;
  justify-content: space-around;
}

.thumbnail-item {
  width: 9%;
  height: 100px;
  max-height: 100px;
  min-height: 20px;
  border: 2px solid #ebeef5;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  background-color: white;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.thumbnail-item:hover {
  border-color: #409eff;
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.thumbnail-item.active {
  border-color: #409eff;
  box-shadow: 0 0 0 3px #409eff, 0 6px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-5px);
}

.thumbnail-item img {
  width: 100%;
  height: 70px;
  object-fit: cover;
}

.thumbnail-label {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

@media (max-width: 768px) {
  .content {
    padding: 10px;
  }

  .main-display {
    padding: 15px;
  }

  .main-image-container {
    height: 200px;
  }

  .thumbnails-wrapper {
    gap: 5px;
    padding: 5px;
  }

  .thumbnail-item {
    width: 8%;
    height: 40px;
    max-height: 100px;
    min-height: 20px;
  }

  .play-button {
    font-size: 14px;
    padding: 10px 20px;
  }
}
</style>